#!/bin/bash
# 更新hosts中的github，加速对应网络的访问。
function host-update-github ()
{
    local host_new=/tmp/host_new$$
    local ref_host=$1

    # 1. 指定参考的hosts，默认为系统所使用的hosts
    if [[ ! -f "$ref_host" ]]; then
        ref_host=/etc/hosts
    fi
    rm -f /tmp/host_new*

    #touch $host_new && tail -f $host_new &
    cp /etc/hosts /tmp/hosts$$.bak -v

    # 2. 更新github有关的hosts
    echo -e "\e[0;35m --> 开始更新hosts文件(github)\e[0m" # purple
    ## 重新填充github有关的地址
	cat $ref_host | grep -v "github" > $host_new
(
cat <<EOF
# for github
123.321.88.8 github.com
123.321.88.8 api.github.com
123.321.88.8 gist.github.com
123.321.88.8 github.global.ssl.fastly.net
123.321.88.8 objects.githubusercontent.com
123.321.88.8 assets-cdn.github.com
123.321.88.8 raw.githubusercontent.com
123.321.88.8 cloud.githubusercontent.com
123.321.88.8 camo.githubusercontent.com
123.321.88.8 avatars0.githubusercontent.com
123.321.88.8 avatars1.githubusercontent.com
123.321.88.8 avatars2.githubusercontent.com
123.321.88.8 avatars3.githubusercontent.com
123.321.88.8 avatars4.githubusercontent.com
123.321.88.8 avatars5.githubusercontent.com
123.321.88.8 avatars6.githubusercontent.com
123.321.88.8 avatars7.githubusercontent.com
123.321.88.8 avatars8.githubusercontent.com
EOF
) >> $host_new

    for ii in $(sed '/^$/d;/^#/d;/127/d' $host_new | awk '/github/{print $2}')
	do
		getip="$(wget -qO- --post-data="host=$ii" https://www.ipaddress.com/ip-lookup -Uuosbox|grep -Eo '<a href="https://www.ipaddress.com/ipv4/\<[0-9]*(\.[0-9]*){3}\>'|awk -F'/' '{print $5;exit}')"
        echo "$ii"
		if [ "$getip" ];then
            sed -i '/ '$ii'/s$\(.*\) \(.*\)$'$getip' \2$g' $host_new
        else
            echo "---> $ii failed."
        fi
	done

    # 3. 调整格式（可选）
    #cp /dev/null ${host_new}.trim
    #cat $host_new | while read line; do
    #    if [[ ${line:0:1} == '#' ]] || [[ ${#line} == 0 ]] \
    #        || [[ $(echo $line | grep localhost) != "" ]] \
    #        || [[ $(echo $line | grep $HOSTNAME) != "" ]]; then
    #        echo $line >> ${host_new}.trim
    #    else
    #        addr=$(echo $line|awk '{print $2}')
    #        link=$(nslookup "$addr" | sed '/^$/d' | sed -n '$p' | sed -n 's/Address: //gp')
    #        if [[ "$link" != "" ]]; then
    #            printf "%-19s%s\n" $link $addr >> ${host_new}.trim
    #        fi
    #    fi
    #done
    #mv -f ${host_new}.trim ${host_new}

    # 4. 复制至 /etc/hosts
    echo -en "\e[0;35m --> 更新hosts文件完毕，是否将新文件 $host_new 移动至 /etc/hosts[Y/n]:\e[0m" # purple
    read reply
    if [[ ${reply} != "n" ]]; then
        sudo mv /etc/hosts{,.bak}
        sudo cp $host_new /etc/hosts
        echo "以root权限执行'/etc/init.d/networking restart' 以重启网络"
    fi
    echo -e "\e[0;36m --> 全部操作完成，Enjoy!\e[0m" # cyan
}
